import { modelFilter } from './model-filter';
import { CustomModel } from '../types';
import { unique } from './unique';

/**
 * 获取当前定制模型的elementId
 * @param elements
 */
export function getCustomElements(elements: IDP.DB.Types.ElementId[]) {
  return elements.filter((ele) => ['Wardrobe', 'Cabinet', 'WardrobeCopy', 'CabinetCopy'].includes(ele.type));
}

/**
 * 获取当前选中模型
 */
export function getSelectedElements() {
  return getCustomElements(IDP.Custom.DoorCoveringHardware.getSelectedElements());
}

/**
 * 获取当前选中的定制模型
 * @param elements
 */
export function getSelectedCustomModels(elements: IDP.DB.Types.ElementId[]): Promise<CustomModel[]> {
  if (elements.length) {
    return Promise.all(
      elements.map((element) => IDP.Custom.Design.CustomModel.getCustomModelByModelIdAsync(element.id))
    ) as Promise<CustomModel[]>;
  }
  return Promise.resolve([]);
}

/**
 * 获取当前选中模型的预览图
 */
export async function getSelectedModelCoverImage(models: CustomModel[]): Promise<string | undefined> {
  const allDoor = modelFilter(models);
  if (allDoor.length) {
    const productId = unique(allDoor.map((i) => i.productId)).filter((i): i is string => !!i);
    if (productId.length === 1) {
      const productImage = await IDP.Custom.Product.getProductInfoAsync(productId[0]);
      return productImage.sketchImgUrl;
    }
  }
  return undefined;
}
